//
//  FingerprintLock.m
//  ERP
//
//  Created by QA on 15/9/15.
//  Copyright (c) 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "FingerprintLock.h"
#import "DMKeychain.h"

#ifdef __IPHONE_8_0
#import <LocalAuthentication/LocalAuthentication.h>
#endif

static FingerprintLock* instance;
static const NSString* KEYCHAIN_NAME = @"passcode";

@implementation FingerprintLock
PasscodeCompletionBlock _completion;

+ (void)initialize {
    [super initialize];
    instance = [[FingerprintLock alloc] init];
}

+ (void)removePasscode {
    [instance removePasscode];
}

+ (BOOL)openPasscode
{
   return [instance openPasscode];
}

+ (BOOL)isPasscodeSet {
    return [instance isPasscodeSet];
}

+ (BOOL)isSupportTouchID
{
    return [instance isSupportTouchID];
}

+ (void)showPasscodeCompletion:(PasscodeCompletionBlock)completion localizedReason:(NSString*)title
{
    return [instance showPasscodeCompletion:completion localizedReason:title];
}

+ (void)showPasscodeCompletion:(PasscodeCompletionBlock)completion
{
    return [instance showPasscodeCompletion:completion localizedReason:@"通过验证指纹解锁汇基云"];
}

+ (void)verificationPasscodeCompletion:(PasscodeCompletionBlock)completion
{
    return [instance verificationPasscodeCompletion:completion localizedReason:@"通过验证指纹解锁汇基云"];
}


/************************************************************************/

- (void)showPasscodeCompletion:(PasscodeCompletionBlock)completion localizedReason:(NSString*)title
{
    //NSAssert([self isPasscodeSet], @"No passcode set");
    LAContext* context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"";
    
    // no touch id available
    if (![self isSupportTouchID]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该设备不支持指纹解锁" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    // no touch id available
    if (![self isPasscodeSet]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"你未开启指纹解锁" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    //开始验证
    [self verificationPasscodeCompletion:completion localizedReason:title];
}

- (void)verificationPasscodeCompletion:(PasscodeCompletionBlock)completion localizedReason:(NSString*)title
{
    _completion = completion;
    if (!_completion) return;
    
    if (![self isPasscodeSet]) {
        _completion(NO, nil);
        return;
    }
    
    if (![self isSupportTouchID]) {
        _completion(NO, nil);
        return;
    }
    
    LAContext* context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"";
    
    // touch id available
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:title reply:^(BOOL success, NSError* error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                switch (error.code) {
                    case LAErrorUserCancel:
                        _completion(NO, nil);
                        break;
                    case LAErrorSystemCancel:
                        _completion(NO, nil);
                        break;
                    case LAErrorAuthenticationFailed:
                        _completion(NO, error);
                        break;
                    case LAErrorPasscodeNotSet:
                    case LAErrorTouchIDNotEnrolled:
                    case LAErrorTouchIDNotAvailable:
                    case LAErrorUserFallback:
                        _completion(NO, error);
                        break;
                }
            } else {
                _completion(success, nil);
            }
        });
    }];
}

- (void)removePasscode
{
    [[DMKeychain defaultKeychain] removeObjectForKey:KEYCHAIN_NAME];
}

- (BOOL)openPasscode
{
    if ([self isSupportTouchID]) {
        [[DMKeychain defaultKeychain] setObject:@"Yes" forKey:KEYCHAIN_NAME];
        return YES;
    }
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"该设备不支持指纹解锁" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
    return NO;
}

- (BOOL)isPasscodeSet
{
    BOOL ret = [[DMKeychain defaultKeychain] objectForKey:KEYCHAIN_NAME] != nil;
    return ret;
}

- (BOOL)isSupportTouchID
{
    // 判断设备是否支持指纹识别
    LAContext *lac = [[LAContext alloc]init];
    BOOL isSupport = [lac canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:NULL];
    return isSupport;
}

@end
